package cn.newhopedairy.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Neo.Li
 * @date 2020-10-15
 */
@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //多租户插件，注意：放在分页插件之前
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            /**
             * 获取租户 ID 值表达式，只支持单个 ID 值
             *
             * @return 租户 ID 值表达式
             */
            @Override
            public Expression getTenantId() {
                //TODO 从session获取当前用户所属的公司（租户）
                return new LongValue(1);
            }

            /**
             * 获取租户字段名，默认字段名叫: tenant_id
             *
             * @return 租户字段名
             */
            @Override
            public String getTenantIdColumn() {
                return "company_id";
            }

            /**
             * 根据表名判断是否忽略拼接多租户条件，默认都要进行解析并拼接多租户条件
             *
             * @param tableName 表名
             * @return 是否忽略, true:表示忽略，false:需要解析并拼接多租户条件
             */
            @Override
            public boolean ignoreTable(String tableName) {
                //TODO
                return !"TODO".equalsIgnoreCase(tableName);
            }
        }));

        //分页插件，注意：必须设置 MybatisConfiguration#useDeprecatedExecutor = false
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        //乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}
